#include<bits/stdc++.h>
using namespace std;
const int N = 1e6+10;
int read(){
    int res = 0;
    char c = getchar_unlocked();
    while(!isdigit(c)){
        c = getchar_unlocked();
    }
    while(isdigit(c)){
        res = res*10 + c - '0';
        c = getchar_unlocked();
    }
    return res;
}
int a[N];
int ac[N];
int fa[N];
int siz[N];
int siz1[N];
inline int gf(int x) {
    while(x != fa[x])x = fa[x];
    return x;
}
inline void merge(int x,int y){
    int xx = gf(x),yy = gf(y);
    if(xx == yy)return;
    siz[xx] += siz[yy];
    siz[yy] = 0;
    siz1[xx] += siz1[yy];
    siz1[yy] = 0;
    fa[yy] = xx;
}
vector<int> mp[N];
void solve(){
    int n;
    n = read();
    for(int i = 1;i<=n;i++){
        a[i] = read();
        fa[i] = i;
        siz[i] =1;
        siz1[i] = 1;
        ac[i] = a[i];
    }
    stable_sort(ac + 1,ac + 1 + n);
    int tot = unique(ac + 1,ac + 1 + n) - ac - 1;
    for(int i = 1;i<=n;i++){
        a[i] = lower_bound(ac + 1,ac + 1 + tot,a[i]) - ac;
    }
    for(int i = 1;i<=tot;i++){
        mp[i].clear();
    }
    for(int i = 1;i<=n;i++){
        mp[a[i]].push_back(i);
    }
    long long ans = 0;
    for(int i = 1;i<=tot;i++){
        long long ansb = ans;
        random_shuffle(mp[i].begin(),mp[i].end());
        for(int v: mp[i])
        {
            if(a[v%n + 1] <= i){
                merge(v%n + 1,v);
            }
            if(a[v == 1?n:v - 1] <= i){
                merge(v == 1?n:v - 1,v);
            }
        }
        for(int v : mp[i]){
            ans += siz[gf(v)] - 1;
            if(siz1[gf(v)] <= n - 2){
                ans+=2;
            }
            if(siz1[gf(v)] == n - 1){
                ans+=1;
            }
            siz[gf(v)]--;
        }
        //cerr<<ans - ansb<<'\n';
    }
    cout<<ans<<'\n';
}
int main(){
    freopen("forever.in","r",stdin);
    freopen("forever.out","w",stdout);
    int T;
    T = read();
    while(T--){
        solve();
    }
}